﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Threading;

namespace dreametryVersion2
{
    public partial class ucWorkFlow : UserControl
    {
        public ucWorkFlow()
        {
            InitializeComponent();
        }

        //ddeclare variables
        String query;
        int count;
        DataTable data;
        List<Label> listTaskName;
        List<Label> listFlowName;
        List<Button> listButtonUp;
        List<Button> listButtonDown;
        List<Panel> listFlowProgress;
        List<Panel> listWorkFlowPanel;
        List<Label> listTaskFlowNumber;

        public String getWorkFlow(String flowQuery)
        {
            this.Visible = false;

            //Store Query in local
            query = flowQuery;

            //redeclare variables
            listTaskName = new List<Label>();
            listFlowName = new List<Label>();
            listButtonUp = new List<Button>();
            listButtonDown = new List<Button>();
            listFlowProgress = new List<Panel>();
            listWorkFlowPanel = new List<Panel>();
            listTaskFlowNumber = new List<Label>();

            //initialize database
            using (SqlConnection connection = new SqlConnection(global.conString))
            {
                //sql command and fill data to datatable
                SqlCommand command = new SqlCommand(flowQuery, connection);
                command.Connection.Open();
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                data = new DataTable();
                data.Clear();
                adapter.Fill(data);
                count = data.Rows.Count;
            }

            //Clear panel
            pnlContent.Controls.Clear();
            //create objects
            for (int i = 0; i < count; i++)
            {
                Panel taskPanel = new Panel()
                {
                    Dock = DockStyle.Top,
                    Padding = new Padding(0, 5, 10, 5),
                    Height = 90
                };

                Label taskName = new Label()
                {
                    Dock = DockStyle.Left,
                    Cursor = Cursors.Hand,
                    AutoSize = false,
                    AutoEllipsis = true,
                    ForeColor = Color.White,
                    BackColor = ColorTranslator.FromHtml(global.themeColor),
                    TextAlign = ContentAlignment.MiddleLeft,
                    Padding = new Padding(10, 10, 10, 10),
                    Width = 200,
                    Text = data.Rows[i][3].ToString()
                };
                listTaskName.Add(taskName);
                listTaskName[i].Click += listTaskName_Click;

                Label taskFlowNumber = new Label()
                {
                    AutoSize = true,
                    Dock = DockStyle.Top,
                    ForeColor = ColorTranslator.FromHtml(global.themeColor),
                    TextAlign = ContentAlignment.TopLeft,
                    Padding = new Padding(7,7,0,0)
                };
                listTaskFlowNumber.Add(taskFlowNumber);

                Label taskFlowName = new Label()
                {
                    AutoSize = false,
                    Dock = DockStyle.Fill,
                    ForeColor = ColorTranslator.FromHtml(global.themeColor),
                    TextAlign = ContentAlignment.TopLeft,
                    Padding = new Padding(7,0,0,7),
                    AutoEllipsis = true
                };
                listFlowName.Add(taskFlowName);
                
                Panel workFlowPanel = new Panel()
                {
                    Dock = DockStyle.Fill,
                    BackColor = Color.WhiteSmoke
                }; listWorkFlowPanel.Add(workFlowPanel);

                Panel flowProgress = new Panel()
                {
                    Dock = DockStyle.Left,
                    Width = 0,
                    BackColor = Color.Gainsboro
                }; listFlowProgress.Add(flowProgress);

                 Button buttonUp = new Button()
                {
                    Dock = DockStyle.Right,
                    BackColor = ColorTranslator.FromHtml(global.themeColor),
                    Text = "Up",
                    FlatStyle = FlatStyle.Flat,
                    ForeColor = Color.White,
                    Width = 70,
                    Cursor = Cursors.Hand,
                    TabStop = true
                 }; buttonUp.FlatAppearance.BorderSize = 0;
                listButtonUp.Add(buttonUp);
                listButtonUp[i].Click += listButtonUp_Click;

                Button buttonDown = new Button()
                {
                    Dock = DockStyle.Right,
                    BackColor = ColorTranslator.FromHtml(global.themeColor),
                    Text = "Down",
                    FlatStyle = FlatStyle.Flat,
                    ForeColor = Color.White,
                    Width = 70,
                    Cursor = Cursors.Hand,
                    TabStop = true
                }; buttonDown.FlatAppearance.BorderSize = 0;
                listButtonDown.Add(buttonDown);
                listButtonDown[i].Click += listButtonDown_Click;

                workFlowPanel.Controls.Add(flowProgress);
                flowProgress.Controls.Add(taskFlowName);
                flowProgress.Controls.Add(taskFlowNumber);
                taskPanel.Controls.Add(workFlowPanel);
                taskPanel.Controls.Add(buttonUp);
                taskPanel.Controls.Add(buttonDown);
                taskPanel.Controls.Add(taskName);
                pnlContent.Controls.Add(taskPanel);

                //variables
                int currentFlow = Int32.Parse(data.Rows[i][9].ToString());
                int flowCount;
                
                //get workflow count in database
                String commandText = "SELECT COUNT(*) FROM WorkFlow WHERE taskCategory = '" + data.Rows[i][11].ToString() + "'";

                using (SqlConnection connection = new SqlConnection(global.conString))
                {
                    SqlCommand command = new SqlCommand(commandText, connection);
                    command.Connection.Open();
                    flowCount = Int32.Parse(command.ExecuteScalar().ToString());
                }
                //display
                if (currentFlow == 1)
                {
                    flowProgress.Width = (workFlowPanel.Width / flowCount) * currentFlow;
                    buttonDown.Visible = false;
                    buttonUp.Width = 140;
                }
                else if (flowCount == currentFlow)
                {
                    flowProgress.Dock = DockStyle.Fill;
                    buttonUp.Visible = false;
                    buttonDown.Width = 140;
                }
                else
                {
                    flowProgress.Width = (workFlowPanel.Width / flowCount) * currentFlow;
                }
                //task flow name details
                taskFlowNumber.Text = currentFlow + "/" + flowCount + " " + data.Rows[i][10].ToString();
                taskFlowName.Text = data.Rows[i][8].ToString();
            }

            this.Visible = true;
            this.Focus();

            return "Task count: " + count.ToString();
        }

        public void listTaskName_Click(object sender, EventArgs e)
        {
            Label task = sender as Label;
            int index = listTaskName.IndexOf(task);
            listTaskName[index].BackColor = System.Drawing.ColorTranslator.FromHtml(global.darkerColor(global.themeColor));
            
            frmTaskDetails form = new frmTaskDetails();
            form.Show();

            //send data
            int id = Int32.Parse(data.Rows[index][0].ToString());
            String creator = data.Rows[index][1].ToString();
            String taskname = data.Rows[index][3].ToString();
            String description = data.Rows[index][4].ToString();
            String flow = data.Rows[index][8].ToString();
            String logs = "";
            String link = data.Rows[index][15].ToString();
            DateTime created;
            DateTime.TryParse(data.Rows[index][6].ToString(), out created);
            DateTime updated;
            DateTime.TryParse(data.Rows[index][7].ToString(), out updated);
            form.displayData(id, creator, taskname, description, flow, logs, link, created, updated);
        }

        public void listButtonUp_Click(object sender, EventArgs e)
        {
            Button up = sender as Button;
            int index = listButtonUp.IndexOf(up);
            int count;

            String result = message.YesNo("Level up", "Do you want to level up task " + listTaskName[index].Text + "?");
            if (result == "Yes")
            {
                //validate
                String cmd = "SELECT COUNT(*) FROM ViewEmployeeTaskData WHERE task_id = '" + data.Rows[index][0] + "' AND flow_name='" + listFlowName[index].Text + "'";
                using (SqlConnection connection = new SqlConnection(global.conString))
                {
                    SqlCommand command = new SqlCommand(cmd, connection);
                    command.Connection.Open();
                    count = Int32.Parse(command.ExecuteScalar().ToString());
                }

                if (count > 0)
                {
                    if (listFlowName[index].Text == "Submit PNG for mock-up creation")
                    {
                        message.DropFiles();
                    }
                    if (listFlowName[index].Text == "Finalizing")
                    {
                        frmOutputDescription frm = new frmOutputDescription();
                        String x = frm.show(data.Rows[index][0].ToString());
                        
                        if (x != null)
                        {
                            //add 1 level in database
                            using (SqlConnection conn = new SqlConnection(global.conString))
                            {
                                conn.Open();
                                SqlCommand command = new SqlCommand("AddLevel", conn);
                                command.CommandType = CommandType.StoredProcedure;
                                command.Parameters.Add(new SqlParameter("@taskId", data.Rows[index][0]));
                                command.ExecuteNonQuery();
                            }

                            //colaborate task
                            using (SqlConnection conn = new SqlConnection(global.conString))
                            {
                                conn.Open();
                                SqlCommand command = new SqlCommand("CollaborateTask", conn);
                                command.CommandType = CommandType.StoredProcedure;
                                command.Parameters.Add(new SqlParameter("@taskId", data.Rows[index][0]));
                                command.Parameters.Add(new SqlParameter("@empid", global.employeeID));
                                command.ExecuteNonQuery();
                            }

                            //refresh datatable
                            using (SqlConnection connection = new SqlConnection(global.conString))
                            {
                                SqlCommand command = new SqlCommand(query, connection);
                                SqlDataAdapter adapter = new SqlDataAdapter(command);
                                data = new DataTable();
                                data.Clear();
                                adapter.Fill(data);
                            }

                            try
                            {
                                //get workflow count in database
                                int flowCount;
                                String commandText = "SELECT COUNT(*) FROM WorkFlow WHERE taskCategory = '" + data.Rows[index][11].ToString() + "'";

                                using (SqlConnection connection = new SqlConnection(global.conString))
                                {
                                    SqlCommand command = new SqlCommand(commandText, connection);
                                    command.Connection.Open();
                                    flowCount = Int32.Parse(command.ExecuteScalar().ToString());
                                }

                                //update single dataflow
                                if (flowCount == Int32.Parse(data.Rows[index][9].ToString()))
                                {
                                    listFlowProgress[index].Dock = DockStyle.Fill;
                                }
                                else
                                {
                                    listFlowProgress[index].Dock = DockStyle.Left;
                                    listFlowProgress[index].Width = (listWorkFlowPanel[index].Width / flowCount) * Int32.Parse(data.Rows[index][9].ToString());
                                }
                                //display updated workflow
                                listTaskFlowNumber[index].Text = data.Rows[index][9].ToString() + "/" + flowCount + " " + data.Rows[index][10].ToString();
                                listFlowName[index].Text = data.Rows[index][8].ToString();

                                //buttons
                                if (Int32.Parse(data.Rows[index][9].ToString()) == flowCount)
                                {
                                    listButtonUp[index].Visible = false;
                                    listButtonDown[index].Width = 140;
                                }
                                else if (Int32.Parse(data.Rows[index][9].ToString()) == 1)
                                {
                                    listButtonDown[index].Visible = false;
                                    listButtonUp[index].Width = 140;
                                }
                                else
                                {
                                    listButtonDown[index].Visible = true;
                                    listButtonDown[index].Width = 70;
                                    listButtonUp[index].Visible = true;
                                    listButtonUp[index].Width = 70;
                                }
                            }
                            catch
                            {
                                frmMain master = (frmMain)Application.OpenForms["frmMain"];
                                master.btnRefresh.PerformClick();
                            }
                        }
                    }
                    else
                    {
                        //add 1 level in database
                        using (SqlConnection conn = new SqlConnection(global.conString))
                        {
                            conn.Open();
                            SqlCommand command = new SqlCommand("AddLevel", conn);
                            command.CommandType = CommandType.StoredProcedure;
                            command.Parameters.Add(new SqlParameter("@taskId", data.Rows[index][0]));
                            command.ExecuteNonQuery();
                        }

                        //colaborate task
                        using (SqlConnection conn = new SqlConnection(global.conString))
                        {
                            conn.Open();
                            SqlCommand command = new SqlCommand("CollaborateTask", conn);
                            command.CommandType = CommandType.StoredProcedure;
                            command.Parameters.Add(new SqlParameter("@taskId", data.Rows[index][0]));
                            command.Parameters.Add(new SqlParameter("@empid", global.employeeID));
                            command.ExecuteNonQuery();
                        }

                        //refresh datatable
                        using (SqlConnection connection = new SqlConnection(global.conString))
                        {
                            SqlCommand command = new SqlCommand(query, connection);
                            SqlDataAdapter adapter = new SqlDataAdapter(command);
                            data = new DataTable();
                            data.Clear();
                            adapter.Fill(data);
                        }

                        try
                        {
                            //get workflow count in database
                            int flowCount;
                            String commandText = "SELECT COUNT(*) FROM WorkFlow WHERE taskCategory = '" + data.Rows[index][11].ToString() + "'";

                            using (SqlConnection connection = new SqlConnection(global.conString))
                            {
                                SqlCommand command = new SqlCommand(commandText, connection);
                                command.Connection.Open();
                                flowCount = Int32.Parse(command.ExecuteScalar().ToString());
                            }

                            //update single dataflow
                            if (flowCount == Int32.Parse(data.Rows[index][9].ToString()))
                            {
                                listFlowProgress[index].Dock = DockStyle.Fill;
                            }
                            else
                            {
                                listFlowProgress[index].Dock = DockStyle.Left;
                                listFlowProgress[index].Width = (listWorkFlowPanel[index].Width / flowCount) * Int32.Parse(data.Rows[index][9].ToString());
                            }
                            //display updated workflow
                            listTaskFlowNumber[index].Text = data.Rows[index][9].ToString() + "/" + flowCount + " " + data.Rows[index][10].ToString();
                            listFlowName[index].Text = data.Rows[index][8].ToString();

                            //buttons
                            if (Int32.Parse(data.Rows[index][9].ToString()) == flowCount)
                            {
                                listButtonUp[index].Visible = false;
                                listButtonDown[index].Width = 140;
                            }
                            else if (Int32.Parse(data.Rows[index][9].ToString()) == 1)
                            {
                                listButtonDown[index].Visible = false;
                                listButtonUp[index].Width = 140;
                            }
                            else
                            {
                                listButtonDown[index].Visible = true;
                                listButtonDown[index].Width = 70;
                                listButtonUp[index].Visible = true;
                                listButtonUp[index].Width = 70;
                            }
                        }
                        catch
                        {
                            frmMain master = (frmMain)Application.OpenForms["frmMain"];
                            master.btnRefresh.PerformClick();
                        }
                    }
                }
                else
                {
                    message.Ok("Conflict", "The task has already updated by other user, please refresh the page");
                }
            }
        }

        public void listButtonDown_Click(object sender, EventArgs e)
        {
            Button down = sender as Button;
            int index = listButtonDown.IndexOf(down);
            int count;

            String result = message.YesNo("Level down", "Do you want to level down task " + listTaskName[index].Text + "?");
            if (result == "Yes")
            {
                //validate
                String cmd = "SELECT COUNT(*) FROM ViewEmployeeTaskData WHERE task_id = '" + data.Rows[index][0] + "' AND flow_name='" + listFlowName[index].Text + "'";
                using (SqlConnection connection = new SqlConnection(global.conString))
                {
                    SqlCommand command = new SqlCommand(cmd, connection);
                    command.Connection.Open();
                    count = Int32.Parse(command.ExecuteScalar().ToString());
                }
                if (count > 0)
                {
                    //decrement 1 in database
                    using (SqlConnection conn = new SqlConnection(global.conString))
                    {
                        conn.Open();
                        SqlCommand command = new SqlCommand("DecLevel", conn);
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.Add(new SqlParameter("@taskId", data.Rows[index][0]));
                        command.ExecuteNonQuery();
                    }

                    //colaborate task
                    using (SqlConnection conn = new SqlConnection(global.conString))
                    {
                        conn.Open();
                        SqlCommand command = new SqlCommand("CollaborateTask", conn);
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.Add(new SqlParameter("@taskId", data.Rows[index][0]));
                        command.Parameters.Add(new SqlParameter("@empid", global.employeeID));
                        command.ExecuteNonQuery();
                    }

                    //refresh datatable
                    using (SqlConnection connection = new SqlConnection(global.conString))
                    {
                        SqlCommand command = new SqlCommand(query, connection);
                        SqlDataAdapter adapter = new SqlDataAdapter(command);
                        data = new DataTable();
                        data.Clear();
                        adapter.Fill(data);
                    }

                    try
                    {
                        //get workflow count in database
                        int flowCount;
                        String commandText = "SELECT COUNT(*) FROM WorkFlow WHERE taskCategory = '" + data.Rows[index][11].ToString() + "'";

                        using (SqlConnection connection = new SqlConnection(global.conString))
                        {
                            SqlCommand command = new SqlCommand(commandText, connection);
                            command.Connection.Open();
                            flowCount = Int32.Parse(command.ExecuteScalar().ToString());
                        }

                        //update single dataflow
                        if (flowCount == Int32.Parse(data.Rows[index][9].ToString()))
                        {
                            listFlowProgress[index].Dock = DockStyle.Fill;
                        }
                        else
                        {
                            listFlowProgress[index].Dock = DockStyle.Left;
                            listFlowProgress[index].Width = (listWorkFlowPanel[index].Width / flowCount) * Int32.Parse(data.Rows[index][9].ToString());
                        }
                        //display updated workflow
                        listTaskFlowNumber[index].Text = data.Rows[index][9].ToString() + "/" + flowCount + " " + data.Rows[index][10].ToString();
                        listFlowName[index].Text = data.Rows[index][8].ToString();

                        //buttons
                        if (Int32.Parse(data.Rows[index][9].ToString()) == flowCount)
                        {
                            listButtonUp[index].Visible = false;
                            listButtonDown[index].Width = 140;
                        }
                        else if (Int32.Parse(data.Rows[index][9].ToString()) == 1)
                        {
                            listButtonDown[index].Visible = false;
                            listButtonUp[index].Width = 140;
                        }
                        else
                        {
                            listButtonDown[index].Visible = true;
                            listButtonDown[index].Width = 70;
                            listButtonUp[index].Visible = true;
                            listButtonUp[index].Width = 70;
                        }
                    }
                    catch
                    {
                        frmMain master = (frmMain)Application.OpenForms["frmMain"];
                        master.btnRefresh.PerformClick();
                    }
                }
                else
                {
                    message.Ok("Conflict", "The task has already updated by other user, please refresh the page");
                }
            }
        }
    }
}
